package team.seekers.catering.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import team.seekers.catering.common.result.R;
import team.seekers.catering.common.result.ResultCode;
import team.seekers.catering.community.entity.dao.Article;
import team.seekers.catering.community.entity.dto.add.ArticleAddDTO;
import team.seekers.catering.community.entity.dto.query.ArticleQuery;
import team.seekers.catering.community.entity.dto.update.ArticleUpdateDTO;
import team.seekers.catering.community.entity.dto.update.LikeOrCommentUpdateDTO;
import team.seekers.catering.community.entity.vo.info.ArticleInfoVO;
import team.seekers.catering.community.service.ArticleService;

import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 增加一个文章
     */
    @PostMapping("/add")
    public R add(@RequestBody ArticleAddDTO articleAddDTO){
        String id = articleService.add(articleAddDTO);
        return R.success().data("id",id);
    }

    /**
     * 根据id删除一个文章
     */
    @GetMapping("/delete/{articleId}")
    public R delete(@PathVariable("articleId")String id){
        articleService.delete(id);
        return R.success();
    }

    /**
     * 修改一个文章(题目和内容)
     */
    @PostMapping("/updateMain")
    public R updateMain(@RequestBody ArticleUpdateDTO articleUpdateDTO){
        String id = articleService.updateMain(articleUpdateDTO);
        return R.success().data("id",id);
    }

    /**
     * 修改一个文章(点赞和评论)
     */
    @PostMapping("/updateForLikeOrComment")
    public R updateForLikeOrComment(@RequestBody LikeOrCommentUpdateDTO likeOrCommentUpdateDTO){
        String id = articleService.updateForLikeOrComment(likeOrCommentUpdateDTO);
        return R.success().data("id",id);
    }

    /**
     * 根据id查询一个文章
     */
    @GetMapping("/query/{articleId}")
    public R query(@PathVariable("articleId")String id){
        ArticleInfoVO articleInfoVO = articleService.get(id);
        return R.success().data("info", articleInfoVO);
    }

    /**
     * 分页查询所有文章
     */
    @PostMapping("/adminPageArticle/{current}/{limit}")
    public R adminPageArticle(@PathVariable("current") long current,
                            @PathVariable("limit") long limit,
                            @RequestBody ArticleQuery query){
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        if(!StringUtils.isNullOrEmpty(query.getNameKey())){
            wrapper.like("name",query.getNameKey());
        }
        Map<String, Object> map = articleService.adminPageArticle(current,limit,wrapper);
        if(map == null){
            return R.fail(ResultCode.GET_FAIL);
        }
        return R.success(map);
    }
}
